package com.bolt.admin.common.base;

import com.bolt.common.BoltConstants;
import com.bolt.convention.data.DefaultResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/24.
 */
public class SimpleController  implements ServletContextAware {


    @Autowired
    protected MessageSource messageSource;

    protected ServletContext servletContext;



    protected void addMessage(String key, Object message) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        requestAttributes.setAttribute(key, message, 0);
    }


    protected void addMessage(DefaultResultMessage message) {
        addMessage(BoltConstants.DEFAULT_MESSAGE, message);
    }


    /**
     * 模块首页跳转
     * 　系统主界页通PJAX实现，本方法主要兼容PJAX加载与刷新加载
     *
     * @param url     跳转地址
     * @param request
     * @param model   　请求参数
     * @return　返回跳转页面
     */
    protected ModelAndView index(String url, HttpServletRequest request, Map<String, ?> model) {
        String pjaxHeader = request.getHeader("X-PJAX");
        //浏览器支持Pjax功能，直接渲染输出页面。
        if ((pjaxHeader != null) && (Boolean.valueOf(pjaxHeader))) {
            ModelAndView modelAndView = new ModelAndView(url);
            modelAndView.addAllObjects(model);
            return modelAndView;
        } else {
            //浏览器不支持Pjax功能或F5刷新页面，使用默认的链接响应机制（加载模板）
            ModelAndView modelAndView = new ModelAndView(BoltConstants.DEFAULT_MAIN_VIEW_TEMPLATEDIR);
            modelAndView.addObject("include", BoltConstants.VEIW_BASE_PATH + url);
            return modelAndView;
        }
    }


    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public ServletContext getServletContext(){
        return this.servletContext;
    }
}
